<template>
	<!-- 我的/登录 -->
	<view class="login">
		<!-- 登录logo：猫头鹰蒙眼睛 -->
		<blindfold :show.sync="showEye"></blindfold>
		<!-- 登录表单 -->
		<view class="login-form wrap-card">
			<u--input :placeholder="loginType === '1' ? '请输入昵称' : '请输入手机号'" border="bottom"
				v-model="form.username" placeholderStyle="{color:'#808080'}" :customStyle="{height:'80rpx'}" clearable>
			</u--input>
			<!-- 密码登录 -->
			<u-input v-if="loginType === '1'" type="password" placeholder="请输入密码" border="bottom"
				v-model="form.password" placeholderStyle="{color:'#808080'}" :customStyle="{height:'80rpx'}" clearable
				@focus="hideEye(true)" @blur="hideEye(false)">
			</u-input>
			<!-- 验证码登录 -->
			<u-input v-if="loginType === '2'" type="password" placeholder="请输入验证码" border="bottom" v-model="form.code"
				placeholderStyle="{color:'#808080'}" :customStyle="{height:'80rpx'}" clearable @focus="hideEye(true)"
				@blur="hideEye(false)">
				<template slot="suffix">
					<u-code ref="uCode" @change="codeChange" seconds="20" changeText="X秒后重新获取" keepRunning
						uniqueKey="login-form"></u-code>
					<u-button @tap="getCode" :text="tips" type="success"></u-button>
				</template>
			</u-input>
		</view>
		<!-- 登录按钮 -->
		<u-button :customStyle="btnStyle" :ripple="true" shape="circle" @click="submit()">登录
		</u-button>
		</u-button>
		<!-- 登录切换 -->
		<view class="flex justify-center items-center mt-50 text-green-400">
			<view class="" @click="changeType()">
				{{loginType === '1' ? '验证码登录' : '密码登录'}}
			</view>
		</view>
	</view>
</template>

<script>
import { UserApi } from '@/api';
export default {
	data() {
		return {
			loginType: '1', // 1:密码 2:验证码
			tips: '',
			showEye: false,
			form: {
				username: '',
				password: '',
				code: ''
			},
			btnStyle: {
				width: "90%",
				height: "100rpx",
				marginTop: '50rpx',
				background: "linear-gradient(-45deg,#01906c,#34D399)",
				color: "#FFFFFF",
				fontSize: "30rpx",
			},
			ws: null
		}
	},
	methods: {
		// 初始化 WebSocket 连接
		initWebSocket(phone) {
		  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
		    return; // 如果已有连接，则不再新建
		  }
		
		  const wsUrl = `ws://192.168.1.109:9007/ws/${phone}`;
		  this.ws = new WebSocket(wsUrl);
		
		  this.ws.onopen = () => {
		    console.log('WebSocket connection opened');
		  };
		
		  this.ws.onmessage = (event) => {
		    const data = JSON.parse(event.data);
		    if (data.messageType === 4) {
		      const codeMatch = data.message.match(/(\d+)/);
		      if (codeMatch && codeMatch[1]) {
		        const code = codeMatch[1];
				uni.showModal({
				    title: '验证码已接收',
				    content: `验证码为：${code}`,
				    showCancel: false,
				    success: (res) => {
				        if (res.confirm) {
							this.form.code = code;
				        }
				    }
				});

		        this.$refs.uCode?.end?.();
		
		        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
		          this.ws.close();
		        }
		      } else {
		        uni.$u.toast('验证码格式错误');
		      }
		    }
		  };
		
		  this.ws.onerror = (error) => {
		    console.error('WebSocket error:', error);
		  };
		
		  this.ws.onclose = () => {
		    console.log('WebSocket connection closed');
		  };
		},
		// 隐藏眼睛
		hideEye(type) {
			this.showEye = type
		},
		// 切换类型
		changeType() {
			this.loginType = this.loginType === '1' ? '2' : '1'
		},
		// 验证码改变
		codeChange(text) {
			this.tips = text
		},
		// 获取验证码
		async getCode() {
		    const { username } = this.form;
		
		    if (this.$refs.uCode.canGetCode) {
		        // 检查是否输入了内容
		        if (!username.trim()) {
		            uni.$u.toast('请输入手机号');
		            return;
		        }
		
		        const phoneReg = /^1[3-9]\d{9}$/;
		
		        // 检查手机号格式是否正确
		        if (this.loginType === '2' && !phoneReg.test(username)) {
		            uni.$u.toast('手机号格式不正确');
		            return;
		        }
		
		        // 如果上面都通过了，才进行以下操作
		        this.initWebSocket(username);
		        try {
		            uni.$u.toast('验证码已发送');
		            await UserApi.getCode({ phone: username });
		            this.$refs.uCode.start();
		        } catch (error) {
		            uni.$u.toast(error.message || '验证码发送失败');
		        }
		    } else {
		        uni.$u.toast('请倒计时结束后再发送');
		    }
		},
		// 提交登陆
		async submit() {
			const { username, password, code } = this.form;
			const loginType = this.loginType;
		
			// 非空验证
			if (!username.trim()) {
			    uni.$u.toast('请输入用户名/手机号');
			    return;
			}
		
			const phoneReg = /^1[3-9]\d{9}$/;
			if (!phoneReg.test(username) && loginType === '2') {
			    uni.$u.toast('手机号格式不正确');
				return;
			}
		
			// 默认密码 123456 的特殊处理
			const isDefaultPassword = password === '123456';
			if (loginType === '1') {
			    if (!password.trim()) {
			        uni.$u.toast('请输入密码');
			        return;
			    }
	
			    // 如果不是默认密码，则进行强密码验证
			    if (!isDefaultPassword) {
			        const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
			        if (!passwordReg.test(password)) {
			            uni.$u.toast('密码必须包含至少一个字母、一个数字和一个特殊字符，并且长度至少为8个字符');
			            return;
			        }
			    }
			}
		
			if (loginType === '2' && !code.trim()) {
			    uni.$u.toast('请输入验证码');
			    return;
			}
		
			try {
			    // 根据登录类型构造参数
			    let params;
			    if (phoneReg.test(username)) {
			        // 手机号 + 验证码登录
			        params = {
			            phone: username,
			            code
			        };
			    } else {
			        // 用户名 + 密码登录
			        params = {
			            username,
			            password
			        };
			    }
		
			    // 调用 UserApi 的 login 方法
			    const res = await UserApi.login(params);
		
			    if (res.code === 200) {
			        uni.$u.toast('登录成功');
			        uni.setStorageSync('token', res.data);
			        this.setupGlobalRequestHeader();
					
			        setTimeout(() => {
			            uni.switchTab({
			                url: '/pages/home/home'
			            });
			        }, 1000);
			    } else {
			        uni.$u.toast(res.msg || '登录失败');
			    }
			} catch (error) {
			    uni.$u.toast(error.message || '网络异常，请重试');
			    console.error('登录出错:', error);
			}
		},
		// 设置全局请求头
		setupGlobalRequestHeader() {
		    const token = uni.getStorageSync('token');
		    if (token) {
		        uni.addInterceptor('request', {
		            invoke(args) {
		                args.header = {
		                    ...args.header,
		                    'Authorization': `${token}`
		                };
		            }
		        });
		    }
		}
	}
}
</script>


<style lang="scss" scoped>
	.login {
		padding-top: 150rpx;

		.login-form {}

	}
</style>
